package 序列化与反序列化;

import 序列化与反序列化.Teacher;

import java.io.*;
/*
  out.writeObject(t);
  System.out.println(in.readObject());
 */
public class TestObeject序列化 {
    ///本类测试序列号与反序列化
    public static void main(String[] args) {
        m1();//方法一测试序列化:ObjectOutputStream
        m2();//方法二测试反序列化:ObjectInputStream
    }

    private static void m2() {//方法二：反序列化
        ObjectInputStream in = null;//1.声明
        try {
            in =new ObjectInputStream(new FileInputStream("1.txt"));//2.创建
            System.out.println(in.readObject());//$$$$$3.反序列化需要进行打印
            System.out.println("反序列化成功");
        } catch (Exception  e) {
            System.out.println("反序列化失败");
            e.printStackTrace();
        }finally {
            try {
                in.close();//4.关流

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private static void m1() {//方法一：序列化
        ObjectOutputStream out =null;//1.声明并赋值null
        try {
            Teacher t =new Teacher("张老师","女",28,3000.58);//3.创建对象并调用，并赋值
            out = new ObjectOutputStream(new FileOutputStream("1.txt"));//2.创建序列化的流对象try/catch
            //4.使用对象,并传参写出
            out.writeObject(t);
            System.out.println("序列化成功");//try里面提示
        } catch (IOException e) {
            System.out.println("序列化失败");//catch里面提示
            e.printStackTrace();
        }finally {
            try {
                out.close();//5.释放资源

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
